package com.fetech.melon.idfactory.worker.dao;

import com.fetech.melon.dao.mongodb.MongoClient;
import com.fetech.melon.dao.mongodb.Order;
import com.fetech.melon.idfactory.worker.entity.WorkerNodeEntity;
import org.springframework.stereotype.Repository;

import javax.annotation.Resource;
import java.util.Date;

/**
 * DAO for M_WORKER_NODE
 *
 * @author yutianbao
 */
@Repository
public class WorkerNodeDAOImpl implements WorkerNodeDAO {

    private static final String collection = "com.fetech.melon.idfactory.worker.entity.WorkerNodeEntity";
    @Resource
    private MongoClient mongoClient;

    /**
     * Add {@link WorkerNodeEntity}
     */
    public synchronized void addWorkerNode(WorkerNodeEntity workerNodeEntity) {
        WorkerNodeEntity max = mongoClient.findByOne(null, Order.by("id", false), WorkerNodeEntity.class, collection);
        if (null == max) {
            workerNodeEntity.setId(1L);
        } else {
            workerNodeEntity.setId(max.getId() + 1);
        }
        workerNodeEntity.setCreated(new Date());
        workerNodeEntity.setModified(new Date());
        mongoClient.save(workerNodeEntity, collection);
    }

}
